# -*- coding: utf-8 -*-
# בש״ד
#
# Miramar CMS for Django - Part of the Cuba Libre Project
# Copyright (C) 2009, Joshua "jag" Ginsberg <jag@flowtheory.net>
#
# Por mi amor, que inspira a mi cada respiración y que echa de Cuba
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import urlparse
from markdown import Extension, etree
from markdown.treeprocessors import Treeprocessor
from django.conf import settings as site_settings
from django.utils.html import escape
from miramar.models import StoredImage, StoredFile
from miramar import settings

class DjangoImageLibraryProcessor(Treeprocessor):
    def run(self, root):
        iterator = root.getiterator('img')
        for img in iterator:
            src = img.get(u'src')
            if src.startswith(urlparse.urljoin(site_settings.MEDIA_URL,
                                               settings.UPLOAD_IMAGE_TO)):
                # Good candidate
                # Docs say that the DB holds the file path relative to
                # MEDIA_ROOT and that MEDIA_ROOT should be accessible at
                # MEDIA_URL. Brilliant.
                url_stub = src[len(site_settings.MEDIA_URL):]
                if url_stub[0] == '/':
                    url_stub = url_stub[1:]
                try:
                    img_obj = StoredImage.objects.get(thumbnail=url_stub)
                except StoredImage.DoesNotExist:
                    continue
                # Duplicate the present element as a subelement of itself
                # and then morph this into an anchor
                etree.SubElement(img, 'img', img.attrib)
                img.tag = 'a'
                del img.attrib['src']
                img.set('href', img_obj.small.url)
                img.set('class', 'preview')
                iterator.next()
        return root

class DjangoFileLibraryProcessor(Treeprocessor):
    def run(self, root):
        iterator = root.getiterator('a')
        for anchor in iterator:
            try:
                href = anchor.get(u'href')
            except:
                # sometimes it's <a name="">
                continue
            print href
            if href.startswith(urlparse.urljoin(site_settings.MEDIA_URL,
                                                settings.UPLOAD_FILE_TO)):
                # Good candidate
                # Docs say that the DB holds the file path relative to
                # MEDIA_ROOT and that MEDIA_ROOT should be accessible at
                # MEDIA_URL. Brilliant.
                url_stub = href[len(site_settings.MEDIA_URL):]
                if url_stub[0] == '/':
                    url_stub = url_stub[1:]
                print url_stub
                try:
                    file_obj = StoredFile.objects.get(file=url_stub)
                except StoredFile.DoesNotExist:
                    print 'DNE'
                    continue
                try:
                    file_ext = url_stub.rsplit('.',1)[1]
                except IndexError:
                    # no extension. lame.
                    desc, icon_url = settings.FILE_ICONS['default']
                else:
                    desc, icon_url = settings.FILE_ICONS.get(
                        file_ext,
                        settings.FILE_ICONS['default'])
                desc = escape(desc)
                img = etree.SubElement(anchor, 
                                       'img', 
                                       {'alt': desc,
                                        'title': desc,
                                        'src': urlparse.urljoin(
                                            site_settings.MEDIA_URL,
                                            icon_url),
                                        'class': 'fileicon'})
                img.tail = anchor.text
                anchor.text = u''
        return root

class MiramarExtension(Extension):
    def extendMarkdown(self, md, md_globals):
        self.md = md
        img_tree_proc = DjangoImageLibraryProcessor(md)
        file_tree_proc = DjangoFileLibraryProcessor(md)
        md.treeprocessors.add('img_tree_proc', img_tree_proc, '<prettify')
        md.treeprocessors.add('file_tree_proc', file_tree_proc, '<prettify')
        self.md.registerExtension(self)
    
    def reset(self):
        pass

def makeExtension(configs=None):
    return MiramarExtension(configs=configs)
                
                
